package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    AddressBookMapper addressBookMapper;

    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.add(addressBook);
    }

    @Override
    public List<AddressBook> list() {
//        只要用户编号
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<AddressBook> addressBooks= addressBookMapper.find(addressBook);
        return addressBooks;
    }

    @Override
    public AddressBook find() {
//        通过用户编号和default进行查询
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(1)
                .build();
        List<AddressBook> addressBooks= addressBookMapper.find(addressBook);

        return addressBooks.get(0);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);

    }

    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }

    @Override
    public AddressBook findById(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .build();
        List<AddressBook> addressBooks = addressBookMapper.find(addressBook);
        return addressBooks.get(0);
    }

    @Override
    public void updateDefault(Long id) {
//        将之前的修改为 0
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(1)
                .build();
        List<AddressBook> addressBooks = addressBookMapper.find(addressBook);
        if (addressBooks!=null && addressBooks.size()>0) {
            AddressBook old_a=addressBooks.get(0);
            old_a.setIsDefault(0);
            addressBookMapper.update(addressBook);
        }

//        现在的修改为 1
        AddressBook new_a = AddressBook.builder()
                .id(id)
                .isDefault(1)
                .build();
        addressBookMapper.update(new_a);

    }
}
